<template>
	<div style="overflow:auto;height:70vh" class="cashbackBox">
		<div class="operateDiv">
			<p class="operateText"><sup>*</sup>获奖条件:</p>
			<el-radio v-model="awardObtainType" label="0">无</el-radio>
			<el-radio v-model="awardObtainType" label="1" :disabled="activityScenes == '994001'">设置</el-radio>
			<el-select v-model="value" placeholder="" class="setSelect" :disabled="iSelectAward">
				<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
				</el-option>
			</el-select>满
			<el-input :placeholder="value == 1?'请输入金额':'请输入度数'" v-model="obtainMoney" class="setInput" clearable :disabled="iSelectAward">
			</el-input>
			<span class="checkTxt" v-show="showTxt" style="right:47%">请输入1~6位正整数</span>
			<span class="checkTxt" v-show="diffAwardObtain" v-text="diffText" style="right:50%"></span>
		</div>
		<el-card class="box-card" v-if="cashbackType == '986001'">
			<div slot="header" class="clearfix">
				<span>奖项-固定金额</span>
			</div>
			<div class="moneyBox item0" :data-id='items&&items[0]&&(items[0].id||null)' :data-lottery="items&&items[0]&&(items[0].lotteryId)">
				<div class="row">
					返现金额&nbsp;
					<input :value="items&&items[0]&&(items[0].cashbackMoney||null)" type="text" placeholder="请输入金额" class="cashInput num0" :data-first="firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null" @blur="checkNum($event,6,2,'1.00')">
					<span class="txtUnit">元</span>
					<span class="checkTxt" v-text="diffText" style="right:20%" v-show=showDiff(items&&items[0]&&(items[0].cashbackMoney),firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null)></span>
				</div>
			</div>
		</el-card>
		<el-card class="box-card" v-if="cashbackType == '986003'">
			<div slot="header" class="clearfix">
				<span>奖项-百分比金额</span>
			</div>
			<div class="moneyBox item0" :data-id='items&&items[0]&&(items[0].id||null)' :data-lottery="items&&items[0]&&(items[0].lotteryId)">
				<div class="row">
					返现金额&nbsp;
					<!-- <el-input placeholder="请输入金额" class="cashInput num0"></el-input> -->
					<input :value="items&&items[0]&&(items[0].cashbackMoney||null)" type="text" placeholder="请输入金额" class="cashInput num0" :data-first="firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null" @blur="checkNum($event,6,2,'1.00')">
					<span class="txtUnit">%</span>
					<span class="checkTxt" v-text="diffText" style="right:20%" v-show=showDiff(items&&items[0]&&(items[0].cashbackMoney),firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null)></span>
				</div>
			</div>
		</el-card>
		<div class="mxBox" v-if="cashbackType == '986002'">
			<el-card class="box-card" v-for="(item,index) in items" :key="index">
				<div slot="header" class="clearfix">
					<span>奖项{{index+1}}-随机返现金额</span>
					<el-button type="info" class="delBtn" @click="delItem(item.id,index)" v-if="index > 0">删除</el-button>
				</div>
				<div :class="'moneyBox item' + index" :data-id='item.id||null' :data-lottery="item.lotteryId">
					<div class="row">
						返现金额&nbsp;
						<input type="text" placeholder="Min" :class="'mxInput num' + index" :value="getVal(0,item)" :data-first="firstData&&firstData[index]&&firstData[index].cashbackMoney&&firstData[index].cashbackMoney.split(',')[0]" @blur="checkNum($event,6,2,'1.00')">
						&nbsp;~&nbsp;
						<input type="text" placeholder="Max" :class="'mxInput num' + index" :value="getVal(1,item)" :data-first="firstData&&firstData[index]&&firstData[index].cashbackMoney&&firstData[index].cashbackMoney.split(',')[1]" @blur="checkNum($event,6,2,'1.00')">
						<span :class="'checkTxt diffMoney' + index" v-text="diffText" style="right:3%" v-show=showDiff(items&&items[0]&&(items[0].cashbackMoney),firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null)></span>
					</div>
					<div class="row">
						中奖概率&nbsp;
						<input type="text" :class="'mxInput win' + index" :value="item.winningProbability" :data-first="firstData&&firstData[index].winningProbability" @blur="checkNum($event,6,0,1)">
						/100000
						<span class="txt">请输入0～100000作为分子，输入数越大，概率越大</span>
						<span :class="'checkTxt diffRate' + index" v-text="diffText" style="right:3%" v-show=showDiff(items&&items[0]&&(items[0].cashbackMoney),firstData&&firstData[0].cashbackMoney?firstData[0].cashbackMoney:null)></span>
					</div>
				</div>
				
			</el-card>
			<div class="addRow" @click="addRow" v-if="repeatRecord == 0">+&nbsp;&nbsp;新建奖项</div>
		</div>
	</div>
</template>

<script>
import {
  FIND_LOTTERY_BY_CODE,
  DELETE_RED_PACKAGE_OR_COUPONrULE_BY_ID,
  FIND_COUPON_RED_BY_CODE,
  FIND_CASHBACK_BY_CODE,
  ADD_OR_UPDATE_CASHBACK,
  EDIT_LOTTERY,
  DELETE_CASHBACK_BY_ID
} from "@/config/url";
import Bus from "@/bus.js";
import { publicVM } from "_config/public.js";

export default {
  mixins: [publicVM],
  components: {},
  props: ["prizeID", "awardSort", "lotterData"],
  data() {
    return {
      giftID: null,
      itemObj: null,
      btnType: "3",
      value: 1,
      value1: "1",
      checked: "",
      options: [
        {
          value: 1,
          label: "金额"
        },
        {
          value: 2,
          label: "电量"
        }
      ],
      activityScenes:sessionStorage.getItem('activityScenes'),//场景
      prizePos: null, //奖品在列表中的位置
      activityCode: sessionStorage.getItem("activityCode"), //活动code
      awardObtainType: "0", //类型
      awardObtain: 0, //获奖条件：0 不限，1金额，2电量
      obtainMoney: null, //满足获奖的金额
      repeatRecord: sessionStorage.getItem("repeatRecord"), //活动复录：0 初录，1 复录
      iSelectAward: true, //是否可以选择获奖条件
      lotteryContent: null, //阶梯内容
      diffText: "与初录不一致",
      diffAwardObtain: false,
      firstID: null,
      pos: null,
      up: null,
      showTxt: false, //显示提示
      cashbackType: sessionStorage.getItem("cashbackType"), //返现类型
      activityCashbacks: [], //提交奖项数据
      maxInput: null,
      minInput: null,
      winningProbability: null, //获奖几率
      lotteryData: [], //阶梯数据
      repeatRecordContent: null, //初录阶梯内容
      tempArr: [] //当前页面数据
    };
  },
  created() {
    let that = this;
    Bus.$on("addItem", data => {
      this.addComPrize(data);
    });
  },
  watch: {
    prizeID(val) {
      this.prizeID = val;
    },
    lotterData(val) {
      let firstData = this.$store.getters.getFirstLotteryData;
      let secData = this.$store.getters.getSecLotteryData;

      if (this.repeatRecord == 0) {
        this.updataData(firstData);
      } else {
        this.repeatRecordContent =
          firstData[sessionStorage.getItem("lotterySort") - 1];
        if (secData) {
          this.updataData(secData);
        }
      }
    },
    obtainMoney(val) {
      this.checkAwardObtain();
    },
    awardObtainType(val) {
      if (val == 1) {
        this.iSelectAward = false;
        if (this.obtainMoney > 0.01) {
          // this.obtainMoney = this.repeatRecordContent.obtainMoney
        } else {
          this.obtainMoney = 0.01;
        }
        this.awardObtain = 1;
      } else {
        this.awardObtain = 0;
        this.iSelectAward = true;
      }
    },
    awardObtain(val) {
      // if(val == 0){
      // 	this.awardObtainType = '0'
      // 	this.obtainMoney = 0
      // 	this.iSelectAward = true
      // }else if(val>0){
      // 	this.awardObtainType = '1'
      // 	this.iSelectAward = false
      // 	this.value = val
      // 	if(this.obtainMoney > 0.01){
      // 		// this.obtainMoney = this.repeatRecordContent.obtainMoney
      // 	}else{
      // 		this.obtainMoney= 0.01
      // 	}
      // }

      // this.diffAward()
      this.checkAwardObtain();
    },
    secData(n, o) {
      if ((n && o && n.toString() !== o.toString()) || n == "") {
        // this.getPrizeID()
      }
    },
    value(val) {
      if (val > 0) {
        this.awardObtain = val;
      }
      this.awardObtain = val;
      this.diffAward();
    }
  },
  computed: {
    items() {
      let firstData = this.$store.getters.getFirstCouponData;
      let secData = this.$store.getters.getSecCouponData;
      if (secData || firstData) {
        if (this.repeatRecord == 0) {
          return firstData;
        } else {
          if (secData) {
            return secData;
          }
        }
      } else {
        return [];
      }
    },
    secData() {
      return this.$store.getters.getSecCouponData;
    },
    firstData() {
      return this.$store.getters.getFirstCouponData;
    },
    secSecPon() {
      return this.$store.getters.getSecLotteryData;
    }
  },
  methods: {
    showDiff(n, o) {
      if (this.repeatRecord == 1) {
        return Number(n) != Number(o);
      } else {
        return false;
      }
    },
    checkAwardObtain() {
      if (this.repeatRecordContent) {
        if (this.awardObtain != this.repeatRecordContent.awardObtain) {
          this.diffAwardObtain = true;
        } else {
          if (this.awardObtain == 0) {
            this.diffAwardObtain = false;
          } else {
            if (this.obtainMoney != this.repeatRecordContent.obtainMoney) {
              this.diffAwardObtain = true;
            } else {
              this.diffAwardObtain = false;
            }
          }
        }
      }
    },
    checkNum(e, w, ws, min) {
      let val1 = Number($(e.target).val());
      if (val1 < Math.pow(10, w) && val1 > 0) {
        if (ws) {
          $(e.target).val(val1.toFixed(ws));
        } else {
          $(e.target).val(Math.ceil(val1));
        }
      } else {
        $(e.target).val(min);
        this.$message({
          message: `请输入1~${w}位正${ws == 0 ? "整" : ""}数`,
          type: "warning"
        });
      }
      if (this.repeatRecord == 1) {
        let fristData = $(e.currentTarget).attr("data-first");
        let val = $(e.currentTarget).val();
        if (fristData != val || val == "") {
          $(e.currentTarget)
            .parent()
            .find(".checkTxt")
            .show();
        } else {
          $(e.currentTarget)
            .parent()
            .find(".checkTxt")
            .hide();
        }
      }
    },
    diffAward() {
      if (
        this.repeatRecord == 0 ||
        (this.repeatRecordContent.awardObtain == this.awardObtain &&
          this.repeatRecordContent.obtainMoney == this.obtainMoney)
      ) {
        this.diffAwardObtain = false;
      } else {
        this.diffAwardObtain = true;
      }
    },
    getPrizeID() {
      if (this.firstData && this.secSecPon && !this.secData) {
        let id = this.$store.getters.getSecLotteryData[
          sessionStorage.getItem("lotterySort") - 1
        ].id;
        if (this.firstData.length != this.secData.length) {
          for (let i = 0; i < this.firstData.length; i++) {
            let item = {};
            item.activityCode = this.activityCode;
            item.lotteryId = id;
            item.winningProbability = null;
            item.cashbackMoney = null;
            item.differentiate = null;
            item.cashbackSort = i + 1;
            item.repeatRecord = this.repeatRecord;
            this.activityCashbacks.push(item);
          }
          this.$post(ADD_OR_UPDATE_CASHBACK, {
            activityCashbacks: this.activityCashbacks
          })
            .then(res => {
              if (res.status == 1) {
                this.getSecLottery();
              } else {
                this.$message({
                  message: res.data,
                  type: "warning"
                });
              }
            })
            .catch(err => {
              console.log(err);
              this.$message({
                message: "操作失败",
                type: "warning"
              });
            });
        }
      }
    },
    getVal(type, item) {
      if (item.cashbackMoney) {
        if (/,/.test(item.cashbackMoney)) {
          let arr = item.cashbackMoney.split(",");
          return arr[type];
        } else {
          return item.cashbackMoney;
        }
      }else{
        return '1.00'
      }
    },
    delItem(id, pos) {
      if (id) {
        this.$fetch(DELETE_CASHBACK_BY_ID, {
          cashbackId: id
        })
          .then(res => {
            if (res.status == 1) {
              Bus.$emit("refreshList");
            } else {
              this.$message({
                message: res.data,
                type: "warning"
              });
            }
          })
          .catch(err => {
            console.log(err);
            this.$message({
              message: "操作失败",
              type: "warning"
            });
          });
      } else {
        this.items.splice(pos, 1);
      }
    },
    addRow(e) {
      if (this.items && this.items.length < 12) {
        // this.newCashback();
        this.savePrize(0,'add');
      } else {
        this.$message({
          message: "最多可添加12个随机返现设置",
          type: "warning"
        });
      }
    },
    addItems() {
      let item = {};
      item.activityCode = this.activityCode;
      item.lotteryId = this.$store.getters.getCurrentLottery;
      item.winningProbability = "1";
      item.cashbackMoney = null;
      item.differentiate = null;
      item.cashbackSort = 1;
      this.items.push(item);
    },
    getIsIdentical(type) {
      let items = null;
      if (type == 0) {
        items = $(
          $(".content .el-tab-pane")[sessionStorage.getItem("lotterySort") - 1]
        ).find(".checkTxt");
      } else {
        items = $(
          $(".content .el-tab-pane")[this.$store.getters.getPreLotterySort - 1]
        ).find(".checkTxt");
      }
      let isSame = false;
      for (let i = 0; i < items.length; i++) {
        if ($(items[i]).css("display") != "none") {
          isSame = true;
          break;
        }
      }
      return isSame;
    },
    getDiffAwardObtain() {
      return this.diffAwardObtain;
    },
    checkPrize() {
      //查看是否添加数据，决定了tab切换
      //   if (this.repeatRecord == 1) {
      let currentDom = $(".content .el-tab-pane")[
        sessionStorage.getItem("lotterySort") - 1
      ];
      let cards = $(currentDom).find(".el-card");
      for (let i = 0; i < cards.length; i++) {
        let nums = $(currentDom).find(".num" + i);
        let win = false;
        if (nums.length > 1) {
          if ($(nums[0]).val() == "" || $(nums[1]).val() == "") {
            return false;
          }
        } else {
          return $(nums).val() != "";
        }

        if (sessionStorage.getItem("cashbackType") == "986002") {
          return (
            $(currentDom)
              .find(".win" + i)
              .val() != ""
          );
        }
      }
      //   } else {
      //     return false;
      //   }
    },
    newCashback() {
      let arr = [];
      let currentDom = $(".content .el-tab-pane")[
        this.$store.getters.getPreLotterySort - 1
      ];
      let cards = $(currentDom).find(".el-card");
      for (let i = 0; i < cards.length; i++) {
        let item = {};

        let nums = $(currentDom).find(".num" + i);
        item.cashbackMoney =
          nums.length > 1
            ? `${$(nums[0]).val()},${$(nums[1]).val()}`
            : $(nums).val();
        if (sessionStorage.getItem("cashbackType") == "986002") {
          item.winningProbability = $(currentDom)
            .find(".win" + i)
            .val();
        }
        item.cashbackSort = i + 1;
        arr.push(item);
      }
      this.tempArr = arr;
    },
    savePrize(type,act) {
      //type  0保存或下一步 1切换阶梯
      this.activityCashbacks = [];
      let currentDom = null;
      if (type == 0) {
        currentDom = $(".content .el-tab-pane")[
          sessionStorage.getItem("lotterySort") - 1
        ];
      } else {
        currentDom = $(".content .el-tab-pane")[
          this.$store.getters.getPreLotterySort - 1
        ];
      }
      let cards = $(currentDom).find(".el-card");
      for (let i = 0; i < cards.length; i++) {
        let item = {};

        let id = $(currentDom)
          .find(".item" + i)
          .attr("data-id");
        if (id) {
          item.id = id;
        }
        item.activityCode = this.activityCode;
        item.lotteryId = $(currentDom)
          .find(".item" + i)
          .attr("data-lottery");
        if (sessionStorage.getItem("cashbackType") == "986002") {
          item.winningProbability = $(currentDom)
            .find(".win" + i)
            .val();
        }
        let nums = $(currentDom).find(".num" + i);
        item.cashbackMoney =
          nums.length > 1
            ? `${$(nums[0]).val()},${$(nums[1]).val()}`
            : $(nums).val();
        item.differentiate = sessionStorage.getItem("cashbackType");
        item.cashbackSort = i + 1;
        if (this.repeatRecord == 0) {
          item.isIdentical = 0;
        } else {
          item.isIdentical = this.getIsIdentical(type) ? 1 : 0;
        }
        item.repeatRecord = this.repeatRecord;
        this.activityCashbacks.push(item);
        if (
          item.winningProbability == "" ||
          item.cashbackMoney == "," ||
          item.cashbackMoney == ""
        ) {
          this.$message({
            message: "必填项不能为空!",
            type: "warning"
          });
          return ;
        }
      }
      this.addCashback(
        type,
        $(currentDom)
          .find(".item" + 0)
          .attr("data-lottery"),
          act
      );
      this.saveLottery(0);
    },
    addCashback(type, id,act) {
      this.$post(ADD_OR_UPDATE_CASHBACK, {
        activityCashbacks: this.activityCashbacks
      })
        .then(res => {
          if (res.status == 1) {
            // this.saveLottery(type)
            if(act == 'add'){

              Bus.$emit("refreshCoupon", id);
            }
          } else {
            this.$message({
              message: res.data,
              type: "warning"
            });
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "操作失败",
            type: "warning"
          });
        });
    },
    saveItem(type) {
      if (this.awardObtain == 0) {
        this.obtainMoney == null;
      }
      let item = {};
      item.activityCode = this.activityCode;
      item.awardObtain = this.awardObtain;
      item.obtainMoney = this.obtainMoney;
      item.repeatRecord = sessionStorage.getItem("repeatRecord");
      item.awardSort = this.awardSort;
      item.repeatRecord = this.repeatRecord;
      item.isIdentical =
        this.repeatRecord == 0 ? 0 : this.getDiffAwardObtain() ? 1 : 0;
      if (type == 0) {
        //点击保存或下一步
        item.id = this.$store.getters.getCurrentLottery;
      } else {
        item.id = this.$store.getters.getPreLottery;
      }

      this.lotteryData = [];
      this.lotteryData.push(item);
    },
    saveLottery(type) {
      this.saveItem(type);
      this.$post(EDIT_LOTTERY, {
        activityLotterys: this.lotteryData
      })
        .then(res => {
          if (res.status == 1) {
            this.$message({
              message: res.data,
              type: "success"
            });
          } else {
            this.$message({
              message: res.data,
              type: "warning"
            });
          }
        })
        .catch(err => {
          console.log(err);
          this.$message({
            message: "获取code失败",
            type: "warning"
          });
        });
    },
    updataData(data) {
      if (data) {
        this.lotteryContent =
          data[sessionStorage.getItem("lotterySort") * 1 - 1];

        if (this.lotteryContent.awardObtain == 0) {
          this.awardObtainType = "0";
          this.iSelectAward = true;
          this.awardObtain = 0;
          this.obtainMoney = null;
          this.value = 1;
        } else if (this.lotteryContent.awardObtain > 0) {
          this.awardObtainType = "1";
          this.value = this.lotteryContent.awardObtain;
          this.iSelectAward = false;
          this.obtainMoney = this.lotteryContent.obtainMoney;
        }
      }
    }
  },
  beforeDestroy() {
    Bus.$off("addItem");
  }
};
</script>

<style lang="less" scoped>
@import "~_config/mixin.less";

.operateDiv {
  width: 100%;
  margin: auto;
  margin-bottom: 0.08rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: 0;
  position: relative;
}
.checkTxt {
  color: #ff2e2e;
  position: absolute;
  right: -7%;
}

.operateText {
  text-align: end;
  width: 13%;
  margin-right: 0.08rem;
}

.setSelect {
  margin-right: 0.08rem;
  width: 0.7rem;
}
.setInput {
  margin-left: 0.08rem;
  width: 0.7rem;
}

.giveSet {
  color: #3395ff;
  text-decoration: underline;
  cursor: pointer;
}

.redBagDiv .el-checkbox {
  padding-top: 0.03rem;
}
.cashbackBox {
  padding-bottom: 0.4rem;
  .box-card {
    width: 74%;
    margin-left: 9%;
    font-size: 20px;
    font-weight: 400;
    color: rgba(45, 51, 67, 1);
    margin-bottom: 20px;
    .checkTxt {
      // display: none
    }
    .el-card__body {
      padding: 30px 40px 40px;
      .bs();
      .moneyBox {
        .fx(column,space-between,flex-start);
        width: 50%;
        height: 100%;
        .row {
          position: relative;
          width: 100%;
          height: 0.3rem;
          margin-left: 0;
          .fx(row,flex-start);
          .cashInput {
            .wh(242px,40px);
          }
          .mxInput {
            .wh(120px,40px);
          }
          .txtUnit {
            position: absolute;
            font-size: 18px;
            right: 45%;
            padding-left: 3%;
          }
          .txt {
            font-size: 16px;
            font-family: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(255, 46, 46, 1);
            position: absolute;
            right: 17%;
            bottom: -26%;
          }
        }
      }
    }
  }
  .addRow {
    font-size: 20px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 149, 255, 1);
    border: 1px dashed #b5c2ca;
    .wh(74%,56px);
    margin-left: 9%;
    text-align: center;
    line-height: 56px;
    cursor: pointer;
    letter-spacing: 4px;
  }
  .delBtn {
    .wh(90px,32px);
    float: right;
    padding: 3px 0;
  }
}
</style>